﻿using MyCode.Project.Domain.Config;
using MyCode.Project.Domain.Repositories;
using MyCode.Project.Infrastructure.Common;
using MyCode.Project.Infrastructure.Enumeration;
using MyCode.Project.Infrastructure.UnityExtensions;
using MyCode.Project.OutSideService;
using Senparc.NeuChar.Context;
using Senparc.NeuChar.Entities;
using Senparc.NeuChar.Entities.Request;
using Senparc.Weixin.Exceptions;
using Senparc.Weixin.MP;
using Senparc.Weixin.MP.AdvancedAPIs;
using Senparc.Weixin.MP.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyCode.Project.Services.CustomMessageHandler
{
    /// <summary>
    /// 自定义MessageHandler
    /// </summary>
    public partial class CustomMessageHandler
    {
      
        private string GetWelcomeInfo()
        {
          
            return string.Format("欢迎光临，版本号{0}", 1);
        }

        private static string accessToken1 = "";
        /// <summary>
        /// 处理文字请求
        /// </summary>
        /// <param name="requestMessage">请求消息</param>
        /// <returns></returns>
        public override IResponseMessageBase OnTextRequest(RequestMessageText requestMessage)
        {
            //return new SuccessResponseMessage();
            //说明：实际项目中这里的逻辑可以交给Service处理具体信息，参考OnLocationRequest方法或/Service/LocationSercice.cs
            string agentUrl = "";
            var defaultResponseMessage = base.CreateResponseMessage<ResponseMessageText>();

            var requestHandler =
                requestMessage.StartHandler();
            //关键字不区分大小写，按照顺序匹配成功后将不再运行下面的逻辑
            requestHandler
                .Keyword("OPENID", () =>
                {
                    var openId = requestMessage.FromUserName;//获取OpenId
                    //var userInfo = Senparc.Weixin.MP.AdvancedAPIs.UserApi.Info(appId, openId, Language.zh_CN);
                    defaultResponseMessage.Content = openId;
                    //defaultResponseMessage.Content = string.Format(
                    //    "您的OpenID为：{0}\r\n昵称：{1}\r\n性别：{2}\r\n地区（国家/省/市）：{3}/{4}/{5}\r\n关注时间：{6}\r\n关注状态：{7}",
                    //    requestMessage.FromUserName, userInfo.nickname, (WeixinSex)userInfo.sex, userInfo.country, userInfo.province, userInfo.city, DateTimeHelper.GetDateTimeFromXml(userInfo.subscribe_time), userInfo.subscribe);
                    return defaultResponseMessage;
                })
             .Keyword("余宇波二维码图", () =>
             {                
                 return new  SuccessResponseMessage();
             })

                //.Keyword("中奖人排行榜ABCD", () =>
                //{
                //    SendGroupMessageByOpenId(requestMessage.FromUserName);
                //    return new SuccessResponseMessage();
                //})
                //.Keyword("测试图文消息", () =>
                //{
                //    var openId = requestMessage.FromUserName;//获取OpenId
                //    var _weiXinAuthorizeService = UnityHelper.GetService<IWeiXinAuthorizeService>();
                //    var wechatAccessToken = _weiXinAuthorizeService.GetTokenAndTicket(SystemConfig.WeAppid, SystemConfig.WeAppSecret);
                //    var accessToken = wechatAccessToken.AccessToken;
                //    //string[] list = new string[]{ openId, "o-F5k1mYTljCzbEWqQnPxVdlU0S8", "o-F5k1gDSbLPoQcQVL6eSKHzKKrc" };
                //    string clientmsgid = DateTime.Now.ToString("mmddhhmmss");
                //    //var result = GroupMessageApi.SendGroupMessageByOpenIdAsync(accessToken, GroupMessageType.text, "这是一条群发消息", clientmsgid, 10000, list);
                //    //LogHelper.Info(result.Result);
                //    var result = base.CreateResponseMessage<ResponseMessageNews>();
                //    result.ToUserName = requestMessage.FromUserName;
                //    result.Articles.Add(new Article()
                //    {
                //        Title = "【¥99元】简七0基础理财课，点击此处立即上课",
                //        Description = @"学会钱生钱，利复利，做金钱的女主人",
                //        PicUrl = "https://mmbiz.qpic.cn/mmbiz_jpg/IibNecEM61WukQ7Vo79DAYNtuNoqYoEhqmIa6tRSRa3oWCCsNWTgibhjxRkS78YXQeegr6CiaLMwH0RWuPLSibQIPg/0?wx_fmt=jpeg",
                //        Url = "https://book.gokolab.com/detail/b4ce3258-53ff-448e-a9ad-f93ede7804df"
                //    });

                //    CustomApi.SendNewsAsync(accessToken, openId, result.Articles, 10000, clientmsgid);

                //    return new SuccessResponseMessage();
                //})
                //.Keyword("图", () =>
                // {
                //     var responseMessageImage = base.CreateResponseMessage<ResponseMessageImage>();
                //     responseMessageImage.MsgType = Senparc.NeuChar.ResponseMsgType.Image;
                //     responseMessageImage.Image.MediaId = "LA0z-5xRzF1ni_YcH8bR-ztKnynl1MtrTiwUbx9WD1o";
                //     return responseMessageImage;

                // })
                ////Default不一定要在最后一个
                .Default(() =>
                {
                    return new SuccessResponseMessage();
                });


            return requestHandler.GetResponseMessage() as IResponseMessageBase;
        }


        /// <summary>
        /// Event事件类型请求
        /// </summary>
        public override IResponseMessageBase OnEventRequest(IRequestMessageEventBase requestMessage)
        {
            var strongRequestMessage = RequestMessage as IRequestMessageEventBase;
            IResponseMessageBase responseMessage = null;
            var weixinAppId = "";// SystemConfig.WeAppid;

            switch (strongRequestMessage.Event)
            {
                case Event.ENTER:
                    responseMessage = OnEvent_EnterRequest(RequestMessage as RequestMessageEvent_Enter);
                    break;
                case Event.LOCATION://自动发送的用户当前位置
                    responseMessage = OnEvent_LocationRequest(RequestMessage as RequestMessageEvent_Location);
                    break;
                case Event.subscribe://订阅
                    responseMessage = OnEvent_SubscribeRequest(RequestMessage as RequestMessageEvent_Subscribe);
                    break;
                case Event.unsubscribe://退订
                    responseMessage = OnEvent_UnsubscribeRequest(RequestMessage as RequestMessageEvent_Unsubscribe);
                    break;
                case Event.CLICK://菜单点击
                    responseMessage = CurrentMessageHandlerNode.Execute(RequestMessage, this, weixinAppId) ??
                                        OnEvent_ClickRequest(RequestMessage as RequestMessageEvent_Click);
                    break;
                case Event.scan://二维码
                    responseMessage = OnEvent_ScanRequest(RequestMessage as RequestMessageEvent_Scan);
                    break;
                case Event.VIEW://URL跳转（view视图）
                    responseMessage = OnEvent_ViewRequest(RequestMessage as RequestMessageEvent_View);
                    break;
                case Event.MASSSENDJOBFINISH://群发消息成功
                    responseMessage = OnEvent_MassSendJobFinishRequest(RequestMessage as RequestMessageEvent_MassSendJobFinish);
                    break;
                case Event.TEMPLATESENDJOBFINISH://推送模板消息成功
                    responseMessage = OnEvent_TemplateSendJobFinishRequest(RequestMessage as RequestMessageEvent_TemplateSendJobFinish);
                    break;
                case Event.pic_photo_or_album://弹出拍照或者相册发图
                    responseMessage = OnEvent_PicPhotoOrAlbumRequest(RequestMessage as RequestMessageEvent_Pic_Photo_Or_Album);
                    break;
                case Event.scancode_push://扫码推事件
                    responseMessage = OnEvent_ScancodePushRequest(RequestMessage as RequestMessageEvent_Scancode_Push);
                    break;
                case Event.scancode_waitmsg://扫码推事件且弹出“消息接收中”提示框
                    responseMessage = OnEvent_ScancodeWaitmsgRequest(RequestMessage as RequestMessageEvent_Scancode_Waitmsg);
                    break;
                case Event.location_select://弹出地理位置选择器
                    responseMessage = OnEvent_LocationSelectRequest(RequestMessage as RequestMessageEvent_Location_Select);
                    break;
                case Event.pic_weixin://弹出微信相册发图器
                    responseMessage = OnEvent_PicWeixinRequest(RequestMessage as RequestMessageEvent_Pic_Weixin);
                    break;
                case Event.pic_sysphoto://弹出系统拍照发图
                    responseMessage = OnEvent_PicSysphotoRequest(RequestMessage as RequestMessageEvent_Pic_Sysphoto);
                    break;
                case Event.card_pass_check://卡券通过审核
                    responseMessage = OnEvent_Card_Pass_CheckRequest(RequestMessage as RequestMessageEvent_Card_Pass_Check);
                    break;
                case Event.card_not_pass_check://卡券未通过审核
                    responseMessage = OnEvent_Card_Not_Pass_CheckRequest(RequestMessage as RequestMessageEvent_Card_Not_Pass_Check);
                    break;
                case Event.user_get_card://领取卡券
                    responseMessage = OnEvent_User_Get_CardRequest(RequestMessage as RequestMessageEvent_User_Get_Card);
                    break;
                case Event.user_del_card://删除卡券
                    responseMessage = OnEvent_User_Del_CardRequest(RequestMessage as RequestMessageEvent_User_Del_Card);
                    break;
                case Event.kf_create_session://多客服接入会话
                    responseMessage = OnEvent_Kf_Create_SessionRequest(RequestMessage as RequestMessageEvent_Kf_Create_Session);
                    break;
                case Event.kf_close_session://多客服关闭会话
                    responseMessage = OnEvent_Kf_Close_SessionRequest(RequestMessage as RequestMessageEvent_Kf_Close_Session);
                    break;
                case Event.kf_switch_session://多客服转接会话
                    responseMessage = OnEvent_Kf_Switch_SessionRequest(RequestMessage as RequestMessageEvent_Kf_Switch_Session);
                    break;
                case Event.poi_check_notify://审核结果事件推送
                    responseMessage = OnEvent_Poi_Check_NotifyRequest(RequestMessage as RequestMessageEvent_Poi_Check_Notify);
                    break;
                case Event.WifiConnected://Wi-Fi连网成功
                    responseMessage = OnEvent_WifiConnectedRequest(RequestMessage as RequestMessageEvent_WifiConnected);
                    break;
                case Event.user_consume_card://卡券核销
                    responseMessage = OnEvent_User_Consume_CardRequest(RequestMessage as RequestMessageEvent_User_Consume_Card);
                    break;
                case Event.user_enter_session_from_card://从卡券进入公众号会话
                    responseMessage = OnEvent_User_Enter_Session_From_CardRequest(RequestMessage as RequestMessageEvent_User_Enter_Session_From_Card);
                    break;
                case Event.user_view_card://进入会员卡
                    responseMessage = OnEvent_User_View_CardRequest(RequestMessage as RequestMessageEvent_User_View_Card);
                    break;
                case Event.merchant_order://微小店订单付款通知
                    responseMessage = OnEvent_Merchant_OrderRequest(RequestMessage as RequestMessageEvent_Merchant_Order);
                    break;
                case Event.submit_membercard_user_info://接收会员信息事件通知
                    responseMessage = OnEvent_Submit_Membercard_User_InfoRequest(RequestMessage as RequestMessageEvent_Submit_Membercard_User_Info);
                    break;
                case Event.ShakearoundUserShake://摇一摇事件通知
                    responseMessage = OnEvent_ShakearoundUserShakeRequest(RequestMessage as RequestMessageEvent_ShakearoundUserShake);
                    break;
                case Event.user_gifting_card://卡券转赠事件推送
                    responseMessage = OnEvent_User_Gifting_CardRequest(RequestMessage as RequestMessageEvent_User_Gifting_Card);
                    break;
                case Event.user_pay_from_pay_cell://微信买单完成
                    responseMessage = OnEvent_User_Pay_From_Pay_CellRequest(RequestMessage as RequestMessageEvent_User_Pay_From_Pay_Cell);
                    break;
                case Event.update_member_card://会员卡内容更新事件：会员卡积分余额发生变动时
                    responseMessage = OnEvent_Update_Member_CardRequest(RequestMessage as RequestMessageEvent_Update_Member_Card);
                    break;
                case Event.card_sku_remind://卡券库存报警事件：当某个card_id的初始库存数大于200且当前库存小于等于100时
                    responseMessage = OnEvent_Card_Sku_RemindRequest(RequestMessage as RequestMessageEvent_Card_Sku_Remind);
                    break;
                case Event.card_pay_order://券点流水详情事件：当商户朋友的券券点发生变动时
                    responseMessage = OnEvent_Card_Pay_OrderRequest(RequestMessage as RequestMessageEvent_Card_Pay_Order);
                    break;

                #region 卡券回调

                case Event.giftcard_pay_done:
                    responseMessage = OnEvent_GiftCard_Pay_DoneRequest(RequestMessage as RequestMessageEvent_GiftCard_Pay_Done);
                    break;

                case Event.giftcard_send_to_friend:
                    responseMessage = OnEvent_GiftCard_Send_To_FriendRequest(RequestMessage as RequestMessageEvent_GiftCard_Send_To_Friend);
                    break;

                case Event.giftcard_user_accept:
                    responseMessage = OnEvent_GiftCard_User_AcceptRequest(RequestMessage as RequestMessageEvent_GiftCard_User_Accept);
                    break;

                #endregion

                #region 微信认证事件推送

                case Event.qualification_verify_success://资质认证成功（此时立即获得接口权限）
                    responseMessage = OnEvent_QualificationVerifySuccessRequest(RequestMessage as RequestMessageEvent_QualificationVerifySuccess);
                    break;
                case Event.qualification_verify_fail://资质认证失败
                    responseMessage = OnEvent_QualificationVerifyFailRequest(RequestMessage as RequestMessageEvent_QualificationVerifyFail);
                    break;
                case Event.naming_verify_success://名称认证成功（即命名成功）
                    responseMessage = OnEvent_NamingVerifySuccessRequest(RequestMessage as RequestMessageEvent_NamingVerifySuccess);
                    break;
                case Event.naming_verify_fail://名称认证失败（这时虽然客户端不打勾，但仍有接口权限）
                    responseMessage = OnEvent_NamingVerifyFailRequest(RequestMessage as RequestMessageEvent_NamingVerifyFail);
                    break;
                case Event.annual_renew://年审通知
                    responseMessage = OnEvent_AnnualRenewRequest(RequestMessage as RequestMessageEvent_AnnualRenew);
                    break;
                case Event.verify_expired://认证过期失效通知
                    responseMessage = OnEvent_VerifyExpiredRequest(RequestMessage as RequestMessageEvent_VerifyExpired);
                    break;
                #endregion

                #region 小程序审核事件推送

                case Event.weapp_audit_success://
                    responseMessage = OnEvent_WeAppAuditSuccessRequest(RequestMessage as RequestMessageEvent_WeAppAuditSuccess);
                    break;
                case Event.weapp_audit_fail://
                    responseMessage = OnEvent_WeAppAuditFailRequest(RequestMessage as RequestMessageEvent_WeAppAuditFail);
                    break;
                #endregion
                default:
                    return new SuccessResponseMessage();
            }
            return responseMessage;
        }

        public override IResponseMessageBase OnTextOrEventRequest(RequestMessageText requestMessage)
        {
            // 预处理文字或事件类型请求。
            // 这个请求是一个比较特殊的请求，通常用于统一处理来自文字或菜单按钮的同一个执行逻辑，
            // 会在执行OnTextRequest或OnEventRequest之前触发，具有以下一些特征：
            // 1、如果返回null，则继续执行OnTextRequest或OnEventRequest
            // 2、如果返回不为null，则终止执行OnTextRequest或OnEventRequest，返回最终ResponseMessage
            // 3、如果是事件，则会将RequestMessageEvent自动转为RequestMessageText类型，其中RequestMessageText.Content就是RequestMessageEvent.EventKey

            //if (requestMessage.Content == "OneClick")
            //{
            //    var strongResponseMessage = CreateResponseMessage<ResponseMessageText>();
            //    strongResponseMessage.Content = "您点击了底部按钮。\r\n为了测试微信软件换行bug的应对措施，这里做了一个——\r\n换行";
            //    return strongResponseMessage;
            //}
            return null;//返回null，则继续执行OnTextRequest或OnEventRequest
        }

        /// <summary>
        /// 点击事件
        /// </summary>
        /// <param name="requestMessage">请求消息</param>
        /// <returns></returns>
        public override IResponseMessageBase OnEvent_ClickRequest(RequestMessageEvent_Click requestMessage)
        {
            return new SuccessResponseMessage();
            IResponseMessageBase reponseMessage = null;
            //菜单点击，需要跟创建菜单时的Key匹配

            //switch (requestMessage.EventKey)
            //{
              
                    //                case "SubClickRoot_Text":
                    //                    {
                    //                        var strongResponseMessage = CreateResponseMessage<ResponseMessageText>();
                    //                        reponseMessage = strongResponseMessage;
                    //                        strongResponseMessage.Content = "您点击了子菜单按钮。";
                    //                    }
                    //                    break;
                    //                case "SubClickRoot_News":
                    //                    {
                    //                        var strongResponseMessage = CreateResponseMessage<ResponseMessageNews>();
                    //                        reponseMessage = strongResponseMessage;
                    //                        strongResponseMessage.Articles.Add(new Article()
                    //                        {
                    //                            Title = "您点击了子菜单图文按钮",
                    //                            Description = "您点击了子菜单图文按钮，这是一条图文信息。这个区域是Description内容\r\n可以使用\\r\\n进行换行。",
                    //                            PicUrl = "https://sdk.weixin.senparc.com/Images/qrcode.jpg",
                    //                            Url = "https://sdk.weixin.senparc.com"
                    //                        });

                    //                        //随机添加一条图文，或只输出一条图文信息
                    //                        if (SystemTime.Now.Second % 2 == 0)
                    //                        {
                    //                            strongResponseMessage.Articles.Add(new Article()
                    //                            {
                    //                                Title = "这是随机产生的第二条图文信息，用于测试多条图文的样式",
                    //                                Description = "这是随机产生的第二条图文信息，用于测试多条图文的样式",
                    //                                PicUrl = "https://sdk.weixin.senparc.com/Images/qrcode.jpg",
                    //                                Url = "https://sdk.weixin.senparc.com"
                    //                            });
                    //                        }
                    //                    }
                    //                    break;
                    //                case "SubClickRoot_Music":
                    //                    {
                    //                        //上传缩略图

                    //#if NET45
                    //                        var filePath = "~/Images/Logo.thumb.jpg";
                    //#else   
                    //                        var filePath = "~/wwwroot/Images/Logo.thumb.jpg";
                    //#endif

                    //                        var uploadResult = Senparc.Weixin.MP.AdvancedAPIs.MediaApi.UploadTemporaryMedia(SystemConfig.WeAppid, UploadMediaFileType.thumb,
                    //                                                                    ServerUtility.ContentRootMapPath(filePath));
                    //                        //PS：缩略图官方没有特别提示文件大小限制，实际测试哪怕114K也会返回文件过大的错误，因此尽量控制在小一点（当前图片39K）

                    //                        //设置音乐信息
                    //                        var strongResponseMessage = CreateResponseMessage<ResponseMessageMusic>();
                    //                        reponseMessage = strongResponseMessage;
                    //                        strongResponseMessage.Music.Title = "天籁之音";
                    //                        strongResponseMessage.Music.Description = "真的是天籁之音";
                    //                        strongResponseMessage.Music.MusicUrl = "https://sdk.weixin.senparc.com/Content/music1.mp3";
                    //                        strongResponseMessage.Music.HQMusicUrl = "https://sdk.weixin.senparc.com/Content/music1.mp3";
                    //                        strongResponseMessage.Music.ThumbMediaId = uploadResult.thumb_media_id;
                    //                    }
                    //                    break;
                    //                case "SubClickRoot_Image":
                    //                    {
                    //                        //上传图片
                    //#if NET45
                    //                        var filePath = "~/Images/Logo.jpg";
                    //#else
                    //                        var filePath = "~/wwwroot/Images/Logo.jpg";
                    //#endif

                    //                        var uploadResult = Senparc.Weixin.MP.AdvancedAPIs.MediaApi.UploadTemporaryMedia(SystemConfig.WeAppid, UploadMediaFileType.image,
                    //                                                                     ServerUtility.ContentRootMapPath(filePath));
                    //                        //设置图片信息
                    //                        var strongResponseMessage = CreateResponseMessage<ResponseMessageImage>();
                    //                        reponseMessage = strongResponseMessage;
                    //                        strongResponseMessage.Image.MediaId = uploadResult.media_id;
                    //                    }
                    //                    break;
                    //                case "SendMenu"://菜单消息
                    //                    {
                    //                        ////注意：
                    //                        ////1、此接口可以在任意地方调用（包括后台线程），此处演示为通过
                    //                        ////2、一下"s:"前缀只是 Senparc.Weixin 的内部约定，可以使用 OnTextRequest事件中的 requestHandler.SelectMenuKeyword() 方法自动匹配到后缀（如101）

                    //                        //var menuContentList = new List<SendMenuContent>(){
                    //                        //    new SendMenuContent("101","满意"),
                    //                        //    new SendMenuContent("102","一般"),
                    //                        //    new SendMenuContent("103","不满意")
                    //                        //};
                    //                        //////使用异步接口
                    //                        //CustomApi.SendMenuAsync(appId, OpenId, "请对 Senparc.Weixin SDK 给出您的评价", menuContentList, "感谢您的参与！");

                    //                        reponseMessage = new ResponseMessageNoResponse();//不返回任何消息
                    //                    }
                    //                    break;
                    //                case "SubClickRoot_Agent"://代理消息
                    //                    {
                    //                        ////获取返回的XML
                    //                        //var dt1 = SystemTime.Now;
                    //                        //reponseMessage = MessageAgent.RequestResponseMessage(this, agentUrl, agentToken, RequestDocument.ToString());
                    //                        ////上面的方法也可以使用扩展方法：this.RequestResponseMessage(this,agentUrl, agentToken, RequestDocument.ToString());

                    //                        //var dt2 = SystemTime.Now;

                    //                        //if (reponseMessage is ResponseMessageNews)
                    //                        //{
                    //                        //    (reponseMessage as ResponseMessageNews)
                    //                        //        .Articles[0]
                    //                        //        .Description += string.Format("\r\n\r\n代理过程总耗时：{0}毫秒", (dt2 - dt1).Milliseconds);
                    //                        //}
                    //                    }
                    //                    break;
                    //                case "Member"://托管代理会员信息
                    //                    {
                    //                        ////原始方法为：MessageAgent.RequestXml(this,agentUrl, agentToken, RequestDocument.ToString());//获取返回的XML
                    //                        //reponseMessage = this.RequestResponseMessage(agentUrl, agentToken, RequestDocument.ToString());
                    //                    }
                    //                    break;
                    //                case "OAuth"://OAuth授权测试
                    //                    {
                    //                        var strongResponseMessage = CreateResponseMessage<ResponseMessageNews>();

                    //                        strongResponseMessage.Articles.Add(new Article()
                    //                        {
                    //                            Title = "OAuth2.0测试",
                    //                            Description = "选择下面两种不同的方式进行测试，区别在于授权成功后，最后停留的页面。",
                    //                            //Url = "https://sdk.weixin.senparc.com/oauth2",
                    //                            //PicUrl = "https://sdk.weixin.senparc.com/Images/qrcode.jpg"
                    //                        });

                    //                        strongResponseMessage.Articles.Add(new Article()
                    //                        {
                    //                            Title = "OAuth2.0测试（不带returnUrl），测试环境可使用",
                    //                            Description = "OAuth2.0测试（不带returnUrl）",
                    //                            Url = "https://sdk.weixin.senparc.com/oauth2",
                    //                            PicUrl = "https://sdk.weixin.senparc.com/Images/qrcode.jpg"
                    //                        });

                    //                        var returnUrl = "/OAuth2/TestReturnUrl";
                    //                        strongResponseMessage.Articles.Add(new Article()
                    //                        {
                    //                            Title = "OAuth2.0测试（带returnUrl），生产环境强烈推荐使用",
                    //                            Description = "OAuth2.0测试（带returnUrl）",
                    //                            Url = "https://sdk.weixin.senparc.com/oauth2?returnUrl=" + returnUrl.UrlEncode(),
                    //                            PicUrl = "https://sdk.weixin.senparc.com/Images/qrcode.jpg"
                    //                        });

                    //                        reponseMessage = strongResponseMessage;

                    //                    }
                    //                    break;
                    //                case "Description":
                    //                    {
                    //                        var strongResponseMessage = CreateResponseMessage<ResponseMessageText>();
                    //                        strongResponseMessage.Content = GetWelcomeInfo();
                    //                        reponseMessage = strongResponseMessage;
                    //                    }
                    //                    break;
                    //                case "SubClickRoot_PicPhotoOrAlbum":
                    //                    {
                    //                        var strongResponseMessage = CreateResponseMessage<ResponseMessageText>();
                    //                        reponseMessage = strongResponseMessage;
                    //                        strongResponseMessage.Content = "您点击了【微信拍照】按钮。系统将会弹出拍照或者相册发图。";
                    //                    }
                    //                    break;
                    //                case "SubClickRoot_ScancodePush":
                    //                    {
                    //                        var strongResponseMessage = CreateResponseMessage<ResponseMessageText>();
                    //                        reponseMessage = strongResponseMessage;
                    //                        strongResponseMessage.Content = "您点击了【微信扫码】按钮。";
                    //                    }
                    //                    break;
                    //                case "ConditionalMenu_Male":
                    //                    {
                    //                        var strongResponseMessage = CreateResponseMessage<ResponseMessageText>();
                    //                        reponseMessage = strongResponseMessage;
                    //                        strongResponseMessage.Content = "您点击了个性化菜单按钮，您的微信性别设置为：男。";
                    //                    }
                    //                    break;
                    //                case "ConditionalMenu_Femle":
                    //                    {
                    //                        var strongResponseMessage = CreateResponseMessage<ResponseMessageText>();
                    //                        reponseMessage = strongResponseMessage;
                    //                        strongResponseMessage.Content = "您点击了个性化菜单按钮，您的微信性别设置为：女。";
                    //                    }
                    //                    break;
                    //                case "GetNewMediaId"://获取新的MediaId
                    //                    {
                    //                        var strongResponseMessage = CreateResponseMessage<ResponseMessageText>();
                    //                        try
                    //                        {
                    //                            var result = Senparc.Weixin.MP.AdvancedAPIs.MediaApi.UploadForeverMedia(SystemConfig.WeAppid, ServerUtility.ContentRootMapPath("~/Images/logo.jpg"));
                    //                            strongResponseMessage.Content = result.media_id;
                    //                        }
                    //                        catch (Exception e)
                    //                        {
                    //                            strongResponseMessage.Content = "发生错误：" + e.Message;
                    //                            WeixinTrace.SendCustomLog("调用UploadForeverMedia()接口发生异常", e.Message);
                    //                        }
                    //                    }
                    //                    break;
                    //                default:
                    //                    {
                    //                        var strongResponseMessage = CreateResponseMessage<ResponseMessageText>();
                    //                        strongResponseMessage.Content = "您点击了按钮，EventKey：" + requestMessage.EventKey;
                    //                        reponseMessage = strongResponseMessage;
                    //                    }
                    //                    break;
            //}
            //return new SuccessResponseMessage();

        }

        /// <summary>
        /// 进入事件
        /// </summary>
        /// <param name="requestMessage"></param>
        /// <returns></returns>
        public override IResponseMessageBase OnEvent_EnterRequest(RequestMessageEvent_Enter requestMessage)
        {
            //var responseMessage = ResponseMessageBase.CreateFromRequestMessage<ResponseMessageText>(requestMessage);
            //responseMessage.Content = "您刚才发送了ENTER事件请求。";
            return new SuccessResponseMessage();
        }

        /// <summary>
        /// 位置事件
        /// </summary>
        /// <param name="requestMessage"></param>
        /// <returns></returns>
        public override IResponseMessageBase OnEvent_LocationRequest(RequestMessageEvent_Location requestMessage)
        {
            //这里是微信客户端（通过微信服务器）自动发送过来的位置信息
            //var responseMessage = CreateResponseMessage<ResponseMessageText>();
            // responseMessage.Content = "这里写什么都无所谓，比如：上帝爱你！";
            //return responseMessage;//这里也可以返回null（需要注意写日志时候null的问题）

            return new SuccessResponseMessage();
        }

        /// <summary>
        /// 通过二维码扫描关注扫描事件
        /// </summary>
        /// <param name="requestMessage"></param>
        /// <returns></returns>
        public override IResponseMessageBase OnEvent_ScanRequest(RequestMessageEvent_Scan requestMessage)
        {
           

            return new SuccessResponseMessage();

        }

        /// <summary>
        /// 打开网页事件
        /// </summary>
        /// <param name="requestMessage"></param>
        /// <returns></returns>
        public override IResponseMessageBase OnEvent_ViewRequest(RequestMessageEvent_View requestMessage)
        {
            ////说明：这条消息只作为接收，下面的responseMessage到达不了客户端，类似OnEvent_UnsubscribeRequest
            //var responseMessage = CreateResponseMessage<ResponseMessageText>();
            //responseMessage.Content = "您点击了view按钮，将打开网页：" + requestMessage.EventKey;
            return new SuccessResponseMessage();
        }

        /// <summary>
        /// 群发完成事件
        /// </summary>
        /// <param name="requestMessage"></param>
        /// <returns></returns>
        public override IResponseMessageBase OnEvent_MassSendJobFinishRequest(RequestMessageEvent_MassSendJobFinish requestMessage)
        {
            //var responseMessage = CreateResponseMessage<ResponseMessageText>();
            //responseMessage.Content = "接收到了群发完成的信息。";
            return new SuccessResponseMessage();
        }

        /// <summary>
        /// 订阅（关注）事件
        /// </summary>
        /// <returns></returns>
        public override IResponseMessageBase OnEvent_SubscribeRequest(RequestMessageEvent_Subscribe requestMessage)
        {
            var _weiXinAuthorizeService = UnityHelper.GetService<IWeiXinAuthorizeService>();
            var wechatAccessToken = _weiXinAuthorizeService.GetTokenAndTicket(SystemConfig.WeAppid, SystemConfig.WeAppSecret);
            var _basMemberWxInfoRepository = UnityHelper.GetService<IBasMemberWxInfoRepository>();
            var accessToken = wechatAccessToken.AccessToken;
            var  memberWxinfo = _basMemberWxInfoRepository.SelectFirst(t => t.OpenID == requestMessage.FromUserName && (t.IsDeleted == false || t.IsDeleted == null));
            if (memberWxinfo == null)
            {
                var weinfo = _weiXinAuthorizeService.GetWxUserInfo(requestMessage.FromUserName);
                memberWxinfo = new Domain.Model.BasMemberWxInfo();
                memberWxinfo.ID = Guid.NewGuid();
                memberWxinfo.City = weinfo.City;
                memberWxinfo.Country = weinfo.Country;
                memberWxinfo.Creater = "关注公众号";
                memberWxinfo.CreateTime = DateTime.Now;
                memberWxinfo.Editor = "关注公众号";
                memberWxinfo.EditTime = DateTime.Now;
                memberWxinfo.HeadImgUrl = weinfo.HeadImgUrl;
                memberWxinfo.MemberID = null;
                memberWxinfo.NickName = weinfo.NickName;
                memberWxinfo.OpenID = weinfo.OpenId;
                memberWxinfo.Province = weinfo.Province;
                memberWxinfo.RoleType =(int) LoginRoleType.WeChatPublic;
                memberWxinfo.Sex = weinfo.Sex;
                memberWxinfo.UnionId = weinfo.UnionId;
                memberWxinfo.IsDeleted = false;
                _basMemberWxInfoRepository.Add(memberWxinfo);
            }

            return new SuccessResponseMessage();
        }

        /// <summary>
        /// 退订
        /// 实际上用户无法收到非订阅账号的消息，所以这里可以随便写。
        /// unsubscribe事件的意义在于及时删除网站应用中已经记录的OpenID绑定，消除冗余数据。并且关注用户流失的情况。
        /// </summary>
        /// <returns></returns>
        public override IResponseMessageBase OnEvent_UnsubscribeRequest(RequestMessageEvent_Unsubscribe requestMessage)
        {
            //var _weiXinAuthorizeService = UnityHelper.GetService<IWeiXinAuthorizeService>();
            //var wechatAccessToken = _weiXinAuthorizeService.GetTokenAndTicket(SystemConfig.WeAppid, SystemConfig.WeAppSecret);
            //var _basMemberWxInfoRepository = UnityHelper.GetService<IBasMemberWxInfoRepository>();
            //var accessToken = wechatAccessToken.AccessToken;
            //var memberWxinfo = _basMemberWxInfoRepository.SelectFirst(t => t.OpenID == requestMessage.FromUserName);
            //if (memberWxinfo == null)
            //{
            //    var weinfo = _weiXinAuthorizeService.GetWxUserInfo(requestMessage.FromUserName);
            //    memberWxinfo = new Domain.Model.BasMemberWxInfo();
            //    memberWxinfo.ID = Guid.NewGuid();
            //    memberWxinfo.City = weinfo.City;
            //    memberWxinfo.Country = weinfo.Country;
            //    memberWxinfo.Creater = "退订公众号";
            //    memberWxinfo.CreateTime = DateTime.Now;
            //    memberWxinfo.Editor = "退订公众号";
            //    memberWxinfo.EditTime = DateTime.Now;
            //    memberWxinfo.HeadImgUrl = weinfo.HeadImgUrl;
            //    memberWxinfo.MemberID = null;
            //    memberWxinfo.NickName = weinfo.NickName;
            //    memberWxinfo.OpenID = weinfo.OpenId;
            //    memberWxinfo.Province = weinfo.Province;
            //    memberWxinfo.RoleType = (int)LoginRoleType.WeChatPublic;
            //    memberWxinfo.Sex = weinfo.Sex;
            //    memberWxinfo.UnionId = weinfo.UnionId;
            //    _basMemberWxInfoRepository.Add(memberWxinfo);
            //}

            return new SuccessResponseMessage();
        }

        /// <summary>
        /// 事件之扫码推事件(scancode_push)
        /// </summary>
        /// <param name="requestMessage"></param>
        /// <returns></returns>
        public override IResponseMessageBase OnEvent_ScancodePushRequest(RequestMessageEvent_Scancode_Push requestMessage)
        {
            var responseMessage = base.CreateResponseMessage<ResponseMessageText>();
            responseMessage.Content = "事件之扫码推事件";
           
            return new SuccessResponseMessage();
        }

        /// <summary>
        /// 事件之扫码推事件且弹出“消息接收中”提示框(scancode_waitmsg)
        /// </summary>
        /// <param name="requestMessage"></param>
        /// <returns></returns>
        public override IResponseMessageBase OnEvent_ScancodeWaitmsgRequest(RequestMessageEvent_Scancode_Waitmsg requestMessage)
        {
            var responseMessage = base.CreateResponseMessage<ResponseMessageText>();
            responseMessage.Content = "事件之扫码推事件且弹出“消息接收中”提示框";
            return new SuccessResponseMessage();
        }

        /// <summary>
        /// 事件之弹出拍照或者相册发图（pic_photo_or_album）
        /// </summary>
        /// <param name="requestMessage"></param>
        /// <returns></returns>
        public override IResponseMessageBase OnEvent_PicPhotoOrAlbumRequest(RequestMessageEvent_Pic_Photo_Or_Album requestMessage)
        {
            var responseMessage = base.CreateResponseMessage<ResponseMessageText>();
            responseMessage.Content = "事件之弹出拍照或者相册发图";
            return new SuccessResponseMessage();
        }

        /// <summary>
        /// 事件之弹出系统拍照发图(pic_sysphoto)
        /// 实际测试时发现微信并没有推送RequestMessageEvent_Pic_Sysphoto消息，只能接收到用户在微信中发送的图片消息。
        /// </summary>
        /// <param name="requestMessage"></param>
        /// <returns></returns>
        public override IResponseMessageBase OnEvent_PicSysphotoRequest(RequestMessageEvent_Pic_Sysphoto requestMessage)
        {
            var responseMessage = base.CreateResponseMessage<ResponseMessageText>();
            responseMessage.Content = "事件之弹出系统拍照发图";
            return new SuccessResponseMessage();
        }

        /// <summary>
        /// 事件之弹出微信相册发图器(pic_weixin)
        /// </summary>
        /// <param name="requestMessage"></param>
        /// <returns></returns>
        public override IResponseMessageBase OnEvent_PicWeixinRequest(RequestMessageEvent_Pic_Weixin requestMessage)
        {
            var responseMessage = base.CreateResponseMessage<ResponseMessageText>();
            responseMessage.Content = "事件之弹出微信相册发图器";
            return new SuccessResponseMessage();
        }

        /// <summary>
        /// 事件之弹出地理位置选择器（location_select）
        /// </summary>
        /// <param name="requestMessage"></param>
        /// <returns></returns>
        public override IResponseMessageBase OnEvent_LocationSelectRequest(RequestMessageEvent_Location_Select requestMessage)
        {
            var responseMessage = base.CreateResponseMessage<ResponseMessageText>();
            responseMessage.Content = "事件之弹出地理位置选择器";
            return new SuccessResponseMessage();
        }

        /// <summary>
        /// 事件之发送模板消息返回结果
        /// </summary>
        /// <param name="requestMessage"></param>
        /// <returns></returns>
        public override IResponseMessageBase OnEvent_TemplateSendJobFinishRequest(RequestMessageEvent_TemplateSendJobFinish requestMessage)
        {
            return new SuccessResponseMessage();
           
        }

        #region 微信认证事件推送

        public override IResponseMessageBase OnEvent_QualificationVerifySuccessRequest(RequestMessageEvent_QualificationVerifySuccess requestMessage)
        {
            //以下方法可以强制定义返回的字符串值
            //TextResponseMessage = "your content";
            //return null;

            return new SuccessResponseMessage();//返回"success"字符串
        }

        #endregion


        #region 领取会员卡事件

        public override IResponseMessageBase OnEvent_Submit_Membercard_User_InfoRequest(RequestMessageEvent_Submit_Membercard_User_Info requestMessage)
        {
            var _weiXinAuthorizeService = UnityHelper.GetService<IWeiXinAuthorizeService>();
            var wechatAccessToken = _weiXinAuthorizeService.GetTokenAndTicket(SystemConfig.WeAppid, SystemConfig.WeAppSecret);
            accessToken1 = wechatAccessToken.AccessToken;          
            var result = CardApi.UserinfoGet(accessToken1, requestMessage.CardId, requestMessage.UserCardCode);
            var _userService = UnityHelper.GetService<IUserService>();
            _userService.RegisteredFromSubmitCard(result, requestMessage);
            return new SuccessResponseMessage();//返回"success"字符串
        }

        #endregion


        #region 进入会员卡
      
        public override IResponseMessageBase OnEvent_User_View_CardRequest(RequestMessageEvent_User_View_Card requestMessage)
        {
            var _weiXinAuthorizeService = UnityHelper.GetService<IWeiXinAuthorizeService>();
            var wechatAccessToken = _weiXinAuthorizeService.GetTokenAndTicket(SystemConfig.WeAppid, SystemConfig.WeAppSecret);
            accessToken1 = wechatAccessToken.AccessToken;          
            var result = CardApi.UserinfoGet(accessToken1, requestMessage.CardId, requestMessage.UserCardCode);
            var _userService = UnityHelper.GetService<IUserService>();
            _userService.RegisteredFromViewtCard(result, requestMessage);
            return new SuccessResponseMessage();//返回"success"字符串
        }

        #endregion



    







    }
}
